package xyz.huanggy.minio.upload;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

import javax.annotation.PostConstruct;

@EnableConfigurationProperties
@MapperScan("xyz.huanggy.**.mapper")
@SpringBootApplication
public class MinioUploadApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(MinioUploadApiApplication.class, args);
    }

    @Value("${minio.access-key}")
    private String accessKey;
    @Value("${minio.access-secret}")
    private String accessSecret;

    @PostConstruct
    public void startMinio() {
        try {
            // MinIO 二进制文件路径
            @SuppressWarnings("all")
            String minioCommand = MinioUploadApiApplication.class.getClassLoader().getResource("minio.exe").getPath();
            // 设定 MinIO 启动命令，指定存储目录
            String[] command = {
                    minioCommand,
                    "server",  // 启动 MinIO 服务器
                    "--address",
                    ":9001",
                    "data"    // 存储目录
            };

            // 启动 MinIO 服务
            ProcessBuilder processBuilder = new ProcessBuilder(command);

            // 设置 MinIO 用户名和密码
            processBuilder.environment().put("MINIO_ROOT_USER", accessKey);
            processBuilder.environment().put("MINIO_ROOT_PASSWORD", accessSecret);

            // 将当前 Java 进程的输入/输出传递给 MinIO 进程
            processBuilder.inheritIO();

            // 启动进程
            Process minioProcess = processBuilder.start();

            //程序结束时停止minio进程
            Runtime.getRuntime().addShutdownHook(new Thread(minioProcess::destroy));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}
